<template>
  <div v-if="!item.hidden">
    <!-- 跳转链接 -->
    <template v-if="hasOneShowingChild(item.children,item) && (!onlyOneChild.children||onlyOneChild.noShowingChildren)&&!item.alwaysShow">
      <sidebar-link v-if="onlyOneChild.meta" :to="resolvePath(onlyOneChild.path)">
        <el-menu-item :index="onlyOneChild.index" :class="{'submenu-title-noDropdown':!isNest}">
          <sidebar-line :icon="onlyOneChild.meta.icon||(item.meta&&item.meta.icon)" :title="onlyOneChild.meta.title" />
        </el-menu-item>
      </sidebar-link>
    </template>

    <!-- 存在下级时 -->
    <el-submenu v-else ref="subMenu" :index="item.index" popper-append-to-body>
      <template slot="title">
        <sidebar-line v-if="item.meta" :icon="item.meta && item.meta.icon" :title="item.meta.title" />
      </template>
      <sidebar-item
        v-for="child in item.children"
        :key="child.path"
        :is-nest="true"
        :item="child"
        :base-path="resolvePath(child.path)"
        class="nest-menu"
      />
    </el-submenu>
  </div>
</template>
<script>
import path from 'path'
import SidebarLink from './Link'
import SidebarLine from './Line'

export default {
  name: 'SidebarItem',
  components: {
    SidebarLink,
    SidebarLine
  },
  props: {
    item: {type: Object, required: true}, // 菜单对象
    isNest: {type: Boolean, default: false}, // 是否存在下级菜单
    basePath: {type: String, default: ''}
  },
  methods: {
    // 判断是否有下级菜单
    hasOneShowingChild(children = [], parent) {
      // 判断子节点是否有要显示的
      const showingChildren = children.filter(item => {
        if (item.hidden) {
          return false
        } else {
          this.onlyOneChild = item
          return true
        }
      })
      if (showingChildren.length === 1) {
        return true
      }
      if (showingChildren.length === 0) {
        this.onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return true
      }
      return false
    },
    // 路径解析
    resolvePath(routePath){
      if (tools.isExternalUrl(routePath)) return routePath;
      if (tools.isExternalUrl(this.basePath)) return this.basePath;
      // console.log(path.resolve(this.basePath, routePath));
      return path.resolve(this.basePath, routePath);
    }
  }
}
</script>
<style>
</style>